<template>
  <div class="block"   >
<!--系统名字-->
    <el-menu  class="el-menu-demo" mode="horizontal"
             background-color= "#409EFF" text-color="#fff" active-text-color="#ffd04b">
      <el-menu-item index="4" ></el-menu-item>
      <p style="position: absolute; color: azure;left:43%;top:4px;">重庆轨道交通客流量预测查询</p>
     </el-menu>
<!--站点路线，日期，预测方法选择框-->
    <el-row style="left: 23%;top: 15px">
      <el-cascader ref="preCascader"
                   v-model="preOptionValue"
                   :options="preOptions" clearable
                   :key = "key"
                   placeholder="选择需要预测的线路和站点">
      </el-cascader>
      <el-date-picker v-model="datePre"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd">
      </el-date-picker>


      <el-cascader ref="preMethodCascader"
                   :props="props"
                   :options="preMethod" clearable
                   placeholder="选择预测模型">
      </el-cascader>


      <el-button type="primary" @click="predict">
        预测
      </el-button>
    </el-row>
<!--百度地图-->
    <el-row style="top: 50px; left :15%;width:1050px;height:300px;">
      <div id="subway" style="height: 500px"></div>
    </el-row>
<!--线路预测展示，折线图，评价指标表格-->
    <el-row style="top: 220px; left :13%">
        <el-col :span="11">
          <div id="1" style="top: 70px;width:90%;height:300px;float:left;"
           v-loading="preLineLoading"
           element-loading-text="拼命计算中"
           element-loading-spinner="el-icon-loading"
           ></div>
        </el-col>
        <el-col :span="12">
           <div>
          <el-table  :data="linePreRecord"  style="top: 65px;"  max-height="250"   :row-class-name="lineTableHighLight">
           <el-table-column prop="preMethod" label="预测方法" width="120"></el-table-column>
           <el-table-column prop="mae" label=MAE width="120"></el-table-column>
           <el-table-column prop="mse" label="MSE" width="120"></el-table-column>
           <el-table-column prop="rmse" label="RMSE" width="120"></el-table-column>
         </el-table>
        </div>
        </el-col>
    </el-row>
<!--站点预测展示，折线图，评价指标表格-->
    <el-row style="top: 220px; left :13%">
        <el-col :span="11">
          <div id="2" style="top: 70px;width:90%;height:300px;float:left;"
           v-loading="preStationLoading"
           element-loading-text="拼命计算中"
           element-loading-spinner="el-icon-loading" ></div>
        </el-col>
        <el-col :span="12">
           <div>
          <el-table  :data="stationPreRecord"  style="top: 65px;" max-height="250"    :row-class-name="stationTableHighLight">
           <el-table-column prop="preMethod" label="预测方法" width="120"></el-table-column>
           <el-table-column prop="mae" label=MAE width="120"></el-table-column>
           <el-table-column prop="mse" label="MSE" width="120"></el-table-column>
           <el-table-column prop="rmse" label="RMSE" width="120"></el-table-column>
         </el-table>
        </div>
        </el-col>
    </el-row>
  </div>

</template>


<style>

</style>



<script>

import * as echarts from "echarts";
import { Message } from "element-ui"
import qs from "qs";



export default {
  data:function(){
    return{
      props: { multiple: true },
      bpnnLineLoading:false,
      bpnnStationLoading:false,
      rfLineLoading:false,
      rfStationLoading:false,
      svrLineLoading:false,
      svrStationLoading:false,
      preLineLoading:false,
      preStationLoading:false,
      key :0,
      preOptionValue:[],
      preOptions: [
        {value: '1', label: '1号线', children: [{value: '102', label: '尖顶坡'}, {value: '103', label: '大学城'}]},
        {value: '2', label: '2号线', children: [{value: '202', label: '较场口'}, {value: '203', label: '临江门'}]},

      ],
      // preMethod:[
      //   {value: 'LinearRegression', label: '线性回归'},
      //   {value: 'RegressionTree', label: '回归树'},
      //   {value: 'BPNN', label: '反向传播神经网络'},
      //   {value: 'SVR', label: '支持向量回归'},
      //   {value: 'BayesianRidge', label: '贝叶斯回归'},
      //   {value: 'RandomForest', label: '随机森林'},
      //   {value: 'KNN', label: 'KNN回归'},
      // ],
      preMethod:[
        {value: 'LinearRegression', label: '线性回归'},
        {value: 'RegressionTree', label: '回归决策树'},
        {value: 'BPNN', label: 'BP神经网络'},
        {value: 'BayesianRidge', label: '贝叶斯回归'},
        {value: 'RandomForest', label: '随机森林'},
      ],
      methodDict:{
        LinearRegression:"线性回归",
        RegressionTree:"回归树",
        BPNN:"反向传播神经网络",
        SVR:"支持向量回归",
        BayesianRidge:"贝叶斯回归",
        RandomForest:"随机森林",
        KNN:"KNN回归",
      },
      datePre: '',
      dateCheck:'',
      myCharts: '',
      preData:{
        line:{
          lineID:1,lineName:"一号线",date:"2022-04-16",
          testflow:[200,200,300,400,500,600,700,600,800],
          BPNN: {
            preflow:[200,100,350,440,600,660,760,620,810],
            mse:234,
            rmse:234,
            mae:123,
          },
          // SVR: {
          //   preflow:[200,100,350,440,600,660,760,620,810],
          //   mse:234,
          //   rmse:234,
          //   mae:123,
          // },
          LinearRegression: {
            preflow:[200,130,360,140,460,650,567,457,278],
            mse:234,
            rmse:234,
            mae:123,
          },
          // KNN: {
          //   preflow:[245,125,456,245,789,245,457,809,128],
          //   mse:234,
          //   rmse:234,
          //   mae:123,
          // },
        },
        station:{
          stationID:102,
          stationName:"小什字",
          date:"2022-04-16",
          testflow:[200,200,300,400,500,600,700,600,800],
          BPNN: {
            preflow:[200,100,350,440,600,660,760,620,810],
            mse:234,
            rmse:234,
            mae:123,
          },
          // SVR: {
          //   preflow:[200,100,350,440,600,660,760,620,810],
          //   mse:234,
          //   rmse:234,
          //   mae:123,
          // },
          LinearRegression: {
            preflow:[200,130,360,140,460,650,567,457,278],
            mse:234,
            rmse:234,
            mae:123,
          },
          // KNN: {
          //   preflow:[245,125,456,245,789,245,457,809,128],
          //   mse:234,
          //   rmse:234,
          //   mae:123,
          // },
        },
      },

      lineBest:100000,
      stationBest:100000,
      lineBestIndex:1,
      stationBestIndex:1,

      linePreRecord: [],
      stationPreRecord: [],
    }
  },
  mounted: function () {
    this.drawLine("1",this.preData.line,this.preData.line.lineName,["BPNN","LinearRegression"])
    this.drawLine('2',this.preData.station,this.preData.station.stationName,["BPNN","LinearRegression"])
    this.map()
    this.initial()
  },
  methods:{
    // 绘制地铁图
    map(){
      const  that = this
      //  重庆地图
      const subwayCityName = '重庆';
      const list = BMapSub.SubwayCitiesList;
      let subwaycity = null;
      for (let i = 0; i < list.length; i++) {
        if (list[i].name === subwayCityName) {
        subwaycity = list[i];
        break;
        }
      }
      this.subway = new BMapSub.Subway('subway', subwaycity.citycode);
      this.subway.setZoom(0.8);
      // 添加放缩控件
      const zoomControl = new BMapSub.ZoomControl({
        anchor: BMAPSUB_ANCHOR_BOTTOM_RIGHT,
        // offset: new BMapSub.Size(10, 100)
      });
      this.subway.addControl(zoomControl);

      //设置中心点
      this.subway.setCenter("观音桥")
      //  点击事件
      this.subway.addEventListener('tap', function(e) {
        let stationName = e.station.name
        let lineName = e.station.line.replace(/\(.*?\)/g, '' ).match(/\d+(.\d+)?/g)
        console.log("duhf",lineName)
        let stationID  = -1
        if (lineName==null){
          Message.warning('您选择的站点'+stationName+'所属线路是环线，暂无数据。请重新选择')
        }
        else if(lineName.length!=1){
          Message.warning('您选择的站点'+stationName+'是换乘站，请更换站点，若仍要选择该站点，请到选择框进行选择')
        }
        else{
          for(let index in that.preOptions){
            if(that.preOptions[index].value == lineName[0]){
              for(let i in that.preOptions[index].children){
                if(that.preOptions[index].children[i].label == stationName){
                  stationID = that.preOptions[index].children[i].value
                }
              }
            }
          }
          if(stationID == -1) {
            Message.warning('您选择的'+stationName+"暂时没有数据，请选择其他站点！")
          }
          else{
            console.log(that.preOptionValue,that.key)
            that.preOptionValue = [Number(lineName[0]),stationID]

            that.key = that.key +1
            console.log("在这里", that.preOptionValue,that.key)
            Message.success('您选择了'+lineName[0]+'号线'+stationName)
          }
        }

      });
      this.subway.addEventListener('subwayloaded', function() {
        alert('地铁图加载完成');
      });
    },
    deleteRow(index, rows) {
        rows.splice(index, 1);
      },
    //初试话站点选择框
    initial(){
       this.$axios.get('http://127.0.0.1:8000/api/initial').then((response) => {
          console.log(response.data);
          this.preOptions = response.data["list"];
          this.checkOptions = response.data["list"];
        })
    },
    //预测
    predict(){
      let that =this
      let methods = this.$refs['preMethodCascader'].getCheckedNodes()
      let mehtodList = []
      for(let i in methods){
        mehtodList.push(methods[i].value)
      }
      let methodName = this.$refs['preMethodCascader'].getCheckedNodes()[0].data.label
			let nodesInfo = this.$refs['preCascader'].getCheckedNodes()[0]
      let lineID = nodesInfo.parent.value
      let stationID = nodesInfo.data.value
      let date = this.datePre
      if (new Date(date)< new Date('2018-06-01') || new Date(date)> new Date('2018-06-31')) {
        this.$message.error('日期选择错误，请选择2018年6月')
        return
      }
      this.$message({
          showClose: true,
          message: '开始预测计算，请耐心等待。',
          type: 'success'
        });

      this.preStationLoading =true
      this.preLineLoading = true

      this.$axios.post('http://127.0.0.1:8000/api/predict',
                      {params:{lineID:lineID, stationID:stationID,date:date,methods:JSON.stringify(mehtodList)},
                       })
        .then(res=>{
          this.preData.line = res.data["line"]
          this.preData.station = res.data["station"]
          this.drawLine("1",this.preData.line,this.preData.line.lineName,mehtodList)
          this.preLineLoading = false
          this.drawLine('2',this.preData.station,this.preData.station.stationName,mehtodList)
          this.preStationLoading = false
          that.linePreRecord =[]
          that.stationPreRecord =[]
          for(let i in mehtodList){
            methodName = that.methodDict[mehtodList[i]]
            console.log("line:::",this.preData.line[mehtodList[i]])
            console.log("station:::",this.preData.station[mehtodList[i]])
            this.linePreRecord.push({
              preMethod:methodName,
              mse:this.preData.line[mehtodList[i]].mse,
              rmse:this.preData.line[mehtodList[i]].rmse,
              mae:this.preData.line[mehtodList[i]].mae,})
            this.stationPreRecord.push({
              preMethod:methodName,
              mse:this.preData.station[mehtodList[i]].mse,
              rmse:this.preData.station[mehtodList[i]].rmse,
              mae:this.preData.station[mehtodList[i]].mae,
            })
            if(this.preData.line[mehtodList[i]].rmse<=that.lineBest){
              that.lineBestIndex = that.linePreRecord.length-1
              that.lineBest = this.preData.line[mehtodList[i]].rmse
            }
            if(this.preData.station[mehtodList[i]].rmse<=that.stationBest){
              that.stationBestIndex = that.stationPreRecord.length-1
              that.stationBest = this.preData.station[mehtodList[i]].rmse
            }
          }
          console.log("bets:::",that.lineBestIndex,that.stationBestIndex)
        })

		},
    lineTableHighLight({ row, rowIndex }) {
        if (rowIndex === this.lineBestIndex) {
          return 'success-row';
        }
        return '';
    },
    stationTableHighLight({ row, rowIndex }) {
        if (rowIndex === this.stationBestIndex) {
          return 'success-row';
        }
        return '';
    },

    //绘制折线图
    drawLine(id,data,name,methodList){
      const date = data.date;
      let y_list = []
      y_list.push({
        name:' 历史客流量',
        data: data.testflow,
        type: 'line',
      })
      for(let i in methodList){
        let method = methodList[i]
        let y = {
            name: this.methodDict[method]+'预测客流量',
            data: data[method].preflow,
            type: 'line',
        }
        y_list.push(y)
      }
      console.log("y:::",y_list)
      // 基于准备好的dom，初始化echarts实例
      this.myChart2 = echarts.init(document.getElementById(id))
      // 绘制图表
      this.myChart2.setOption(
        {
        title: {
          text: name, // 主标题
          subtext: '', // 副标题
          x: 'left' // x轴方向对齐方式
        },
        tooltip: {
          trigger: 'axis' // axis   item   none三个值
        },


        xAxis: {
          type: 'category', // 还有其他的type，可以去官网喵两眼哦
          interval:1, // 步长
          min:0, // 起始
          max:data.testflow.length-1, // 终止
          name: '时间段', // x轴名称
        },
        yAxis: {
          type: 'value',
          name: date.toString()+'客流量' // y轴名称
        },
        legend: {
          orient: 'horizontal',
          x: 'left',
          padding:[0,0,0,120]
          // y: 'top',
          // width:20,
          // height:50,
          // orient:'vertical',
          // data: [date+' 实际客流量',
          //   date+' 预测客流量']
        },
        series: y_list

      },
        true
      )
    },


    }
}


</script>



<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
